﻿using Cinemachine;
using UnityEngine;
namespace Core
{
    public class CameraComponent : Entity, IAwake, IUpdate
    {
        #region Field
        private Vector2 speed = new Vector2(2,1);
        private Vector2 delta;
        private Vector3 forward;
        private Unit unit;
        private Transform follow;
        private Transform virtualCameraTransform;
        private CinemachinePOV aim;
        #endregion
        public Vector3 Forward
        {
            get
            {
                // 只需要X和Z轴作为方向
                forward.Set(virtualCameraTransform.forward.x, 0, virtualCameraTransform.forward.z);
                return forward;
            }
        }
        void IAwake.Awake()
        {
            follow = new GameObject("player follow").transform;
            unit = GetParent<Unit>();
            virtualCameraTransform = GameObject.Find("Virtual Camera").transform;
            var virtualCamera = virtualCameraTransform?.GetComponent<CinemachineVirtualCamera>();
            if (virtualCamera != null)
            {
                // 设置虚拟摄像机观看目标
                virtualCamera.LookAt = Player.Instance.GetParent<Unit>().transform;
                // 设置跟随目标
                virtualCamera.Follow = follow;
                aim = virtualCamera.GetCinemachineComponent(CinemachineCore.Stage.Aim) as CinemachinePOV;
            }
        }
        public void SetDelta(Vector2 forward)
        {
            this.delta += forward * speed;
        }
        void IUpdate.Update()
        {
            follow.position = unit.transform.position + Vector3.up;
            // 更新摄像机旋转
            aim.m_VerticalAxis.Value = delta.y;
            aim.m_HorizontalAxis.Value = delta.x;
        }
    }
}